package com.zatech.cgnci.project.base.interceptor;

import com.zatech.cgnci.project.base.utils.VerifyUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * @author user
 */
public class PrefixUrlMapping extends RequestMappingHandlerMapping {

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    static {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        pathMatcher.setPathSeparator(".");
    }

    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        RequestMappingInfo mappingForMethod = super.getMappingForMethod(method, handlerType);
        if (VerifyUtils.isNotEmpty(mappingForMethod)) {
            String packageName = handlerType.getPackage().getName();
            if (isMatching(packageName)) {
                if (packageName.startsWith("com.zatech.cgnci")) {
                    String[] packageNames = packageName.split("\\.");
                    if (packageNames.length >= 4) {
                        return RequestMappingInfo.paths().build().combine(mappingForMethod);
                    }
                }
            }
        }
        return mappingForMethod;
    }

    private boolean isMatching(String packageName) {
        return (PATH_MATCHER.match("com.zatech.cgnci.**.controller", packageName));
    }
}
